<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" :align-center="true" width="50%" :title="`完善企业用户信息`">
    <el-form
      ref="ruleFormRef"
      :rules="rules"
      :disabled="dialogData.isView"
      :model="dialogData.itemInfo"
      label-width="100px"
      label-suffix=" :"
      :hide-required-asterisk="dialogData.isView"
    >
      <el-row :gutter="20">
        <el-col :span="16">
          <el-row>
            <el-col>
              <el-form-item label="登录帐号">
                <el-input v-model="dialogData.itemInfo.account" placeholder="请填写登录帐号" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="身份证号">
                <el-input v-model="dialogData.itemInfo.idCard" placeholder="请填写身份证号" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item>
                <div class="info-wrapper">
                  <el-alert
                    title="为了保证您账号的安全性，开设认证子账号用户需要上传提交使用人的身份证和工作证明或者授权证明。"
                    type="warning"
                    :closable="false"
                    show-icon
                  />
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="img-box">
            <div class="img">
              <UploadImg
                v-model:imageUrl="dialogData.itemInfo.idFront"
                :disabled="dialogData.isView"
                :file-size="3"
                width="300px"
                height="180px"
                :api="uploadUserId"
              >
                <template #tip>身份证不能超过 3M </template>
              </UploadImg>
            </div>
            <div class="opt">
              <el-button type="primary" size="large" :icon="Search" :loading="btnLoading" @click="handleUserIdentity">
                OCR识别 实名身份信息
              </el-button>
            </div>
          </div>
          <el-row>
            <el-col>
              <el-form-item label="姓名">
                <el-input
                  v-model="dialogData.itemInfo.name"
                  placeholder="请填写用户姓名"
                  clearable
                  maxlength="10"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col>
              <el-form-item label="性别">
                <el-radio-group v-model="dialogData.itemInfo.gender">
                  <el-radio v-for="item in genderType" :label="item.value" :key="item.value">{{ item.label }} </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="手机号" prop="phone">
                <el-input
                  v-model="dialogData.itemInfo.phone"
                  placeholder="请填写手机号"
                  clearable
                  maxlength="20"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="邮箱">
                <el-input
                  v-model="dialogData.itemInfo.email"
                  placeholder="请填写邮箱"
                  clearable
                  maxlength="50"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <UploadImg
              v-model:imageUrl="dialogData.itemInfo.avator"
              :disabled="dialogData.isView"
              :file-size="2"
              width="120px"
              height="120px"
            >
              <template #tip> 大小不超 2M </template>
            </UploadImg>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" v-show="!dialogData.isView" @click="handleSubmit" :loading="btnLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import UploadImg from "@/components/Upload/Img.vue";
import { getOptTitle, OptEnum, sysEnum } from "@/biz/eenum/appEnum";
import { DialogParam } from "@/biz/interface/DialogType";
import { CompanyUserEntity } from "@/biz/interface/CompanyType";
import { getUserInfoApi } from "@/api/modules/sys/user";
import { genderType } from "@/biz/datas/sysData";
import { handleCompanyUserIdentityApi, saveCompanyUserApi, saveCompanyUserConfigApi } from "@/api/modules/cpy/act";
import { UserInfoEntity } from "@/biz/interface/userType";
import { uploadUserId } from "@/api/modules/upload";
import { Search } from "@element-plus/icons-vue";

const rules = reactive({
  phone: [{ required: true, message: "手机号不能为空", trigger: "blur" }]
});

//页面的数据
interface UserDialogOption extends DialogParam {
  //弹出表单的标题
  title: string;
  //是否是查看状态，查看状态是不可以提交数据  isView: false,
  isView: boolean;
  //是否是审核状态
  isAudit: boolean;
  //当前的数据对象
  itemInfo: UserInfoEntity;
}

//提交按钮，避免多次提交
const btnLoading = ref(false);
// 弹出框的参数
const dialogVisible = ref(false);
const dialogData = reactive<UserDialogOption>({
  optType: OptEnum.UNKNOW,
  title: "",
  isView: false,
  isAudit: false,
  itemInfo: {
    account: "",
    password: "",
    name: "",
    gender: sysEnum.ONE,
    phone: "",
    idCard: "",
    email: "",
    avator: "",
    auditContent: ""
  }
});

// 接收父组件传过来的参数
const acceptParams = (params: DialogParam): void => {
  dialogData.optType = params.optType;
  dialogData.rowData = params.rowData;

  dialogData.isView = dialogData.optType === OptEnum.VIEW;
  dialogData.isAudit = dialogData.optType === OptEnum.AUDIT;
  dialogData.title = getOptTitle(dialogData.optType);

  if (dialogData.optType === OptEnum.CREATE) {
    initItemInfo();
  } else if (dialogData.rowData && dialogData.rowData.id) {
    getItemInfo(dialogData.rowData.id);
  }

  dialogVisible.value = true;
};

const initItemInfo = (): void => {
  dialogData.itemInfo = {
    account: "",
    password: "",
    name: "",
    gender: sysEnum.ONE,
    phone: "",
    idCard: "",
    email: "",
    avator: "",
    auditContent: ""
  };
};

//获取当前数据的详情，不通过表格上的数据行，直接调用接口获取数据
const getItemInfo = async (id: string) => {
  if (id) {
    //通过接口获取数据
    let { data } = await getUserInfoApi({ id });
    // console.log("接收到服务器端的数据", data);
    dialogData.itemInfo = data as unknown as CompanyUserEntity;
  }
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  btnLoading.value = true;
  ruleFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      if (dialogData.optType === OptEnum.EDIT) {
        //提交数据
        let res = await saveCompanyUserApi({
          ...dialogData.itemInfo
        });
        if (res.data) {
          //去创建一个企业的可配置币的帐号
          saveCompanyUserConfigApi(res.data as string);
          ElMessage.success({ message: `${dialogData.title}用户成功！` });
          //刷新列表数据
          emits("refresh-list");
          dialogVisible.value = false;
        }
      }
    } catch (error) {
      // console.log(error);
    } finally {
      btnLoading.value = false;
    }
  });
};

const handleUserIdentity = async () => {
  let res = await handleCompanyUserIdentityApi({});
  if (res && res.data) {
  }
};

// // 公共校验方法（图片上传成功触发重新校验）
// const checkValidate = (val: string) => {
//   ruleFormRef.value!.validateField(val, () => {});
// };

//页面事件
const emits = defineEmits(["refresh-list"]);

//页面参数
defineExpose({
  acceptParams
});
</script>
<style scoped lang="scss">
.img-box {
  // border: 1px solid red;
  display: flex;
  align-items: center;
  justify-content: space-around;
  margin-bottom: 1rem;

  .img {
    // border: 1px solid red;
    margin-left: 5rem;
  }
  .opt {
    // border: 1px solid green;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 200px;
    height: 180px;
  }
}
</style>
